package com.cl.code.database.mybatis.module.sql.table;

import lombok.Getter;

import java.lang.reflect.Field;

/**
 * @author chengliang
 * @since 1.0.0
 */
@Getter
public abstract class TableField {

    protected final String fieldName;

    protected final String sqlFieldName;

    protected final Field field;

    public TableField(String fieldName, String sqlFieldName, Field field) {
        this.fieldName = fieldName;
        this.sqlFieldName = sqlFieldName;
        this.field = field;
    }

    @SuppressWarnings("unchecked")
    public <T> T getValue(Object entity, Class<T> clazz) {
        try {
            field.setAccessible(true);
            Object o = field.get(entity);
            if (o == null) {
                return null;
            } else if (clazz.isAssignableFrom(o.getClass())) {
                return (T) o;
            } else {
                throw new IllegalArgumentException("field type error");
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public <T> void setValue(Object entity, T value) {
        try {
            field.setAccessible(true);
            Class<?> type = field.getType();
            if (value != null && !type.isAssignableFrom(value.getClass())) {
                throw new IllegalArgumentException("field type error");
            }
            field.set(entity, value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
